﻿Public Class HDViewForm

    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' 
    ''' 
    ''' 
    ''' 
    Dim row As Integer = 0
    Dim dirow As Integer = 0
    Dim FNETID As Integer = 1
    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        If sender.Text = "取消" Then
            sender.Text = "正在取消..."
            sender.Enabled = False
            bwSearch.CancelAsync()
            Exit Sub
        End If

        If CheckValidate() = False Then
            Exit Sub
        End If
        row = 0
        Me.DataGridView1.DataSource = Nothing
        Me.DataGridView1.Columns.Clear()

        BeforeRefreshControlState()
        Me.bwSearch.RunWorkerAsync(New Object() {Me.cboRef.SelectedItem, Me.dtpFrom.Value, Me.dtpTo.Value, Me.cboIntevalType.Text.Trim, Me.cboSecond.Text, Me.nudMinute.Value, Me.nudHour.Value})

    End Sub
    Private Sub BeforeRefreshControlState()
        'Me.DataGridView1.Cursor = Cursors.WaitCursor
        'Me.btnRefresh.Enabled = False
        Me.btnRefresh.Text = "取消"
        Me.dtpFrom.Enabled = False
        Me.dtpTo.Enabled = False
        Me.btnExport.Enabled = False
        Me.cboIntevalType.Enabled = False
        Me.cboRef.Enabled = False
        Me.cboSecond.Enabled = False
        Me.nudHour.Enabled = False
        Me.nudMinute.Enabled = False
        Me.btnPrint.Enabled = False
        Me.pnlSearch.Visible = True
    End Sub
    Private Sub AfterRefreshControlState()
        'Me.pnlSearch.Visible = False
        Me.cboIntevalType.Enabled = True
        Me.cboRef.Enabled = True
        Me.cboSecond.Enabled = True
        Me.nudHour.Enabled = True
        Me.nudMinute.Enabled = True
        'Me.btnExport.Enabled = True
        'Me.btnPrint.Enabled = True
        Me.dtpFrom.Enabled = True
        Me.dtpTo.Enabled = True
        Me.btnRefresh.Enabled = True
        Me.btnRefresh.Text = "查询"
        'Me.DataGridView1.Cursor = Cursors.Default
    End Sub

    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <remarks></remarks>
    Private Function RefreshData(ByVal argument As Object) As Object
        Dim cbo_rti As RefTypeItem = argument(0)
        Dim dtpFromValue As Date = argument(1)
        Dim dtpToValue As Date = argument(2)
        Dim IntevalType As String = argument(3)
        Dim _Second As Integer
        'Dim AI_ColumnName As String
        Dim IsFind As Boolean
        Dim tArray As New ArrayList()
        Dim hArray As New ArrayList()
        If argument(4) = "" Then
            _Second = 0
        Else
            _Second = Convert.ToInt32(argument(4))

        End If
        'Try
        '    _Second = Convert.ToInt32(argument(4))
        'Catch ex As Exception
        '    _Second = 0
        'End Try
        Dim _Minute As Integer = argument(5)
        Dim _Hour As Integer = argument(6)
        Dim strSql As String
        Dim strSql1 As String
        ' Dim lastal As Integer
        'Dim cbo_rti As RefTypeItem = CType(cboRef.SelectedItem, RefTypeItem)
        Dim apts As AiPortTypeService = New AiPortTypeService(cbo_rti)
        Dim alarmstatus_DoorValid As Boolean = False
        Dim alarmstatus_LosPowerValid As Boolean = False
        Dim alarmstatus_RefAlarmValid As Boolean = False
        Dim alarmstatus_SoundAlarmValid As Boolean = False
        'dim kv As KeyValuePair(DateTime, DateTime)
        '***************************************************************************
        Dim DoorState_tablename = String.Format("Ref{0}_DoorAlarm", cbo_rti.RefId.ToString)
        'Dim dtAlBg() As DateTime
        'Dim dtAlEnd() As DateTime
        Dim dtAlBg As New ArrayList
        Dim dtAlEnd As New ArrayList
        Dim right As Boolean = False

        strSql = String.Format("select  distinct netID, startTime, Ref{0}_DoorAlarm from tbccHDAlarmData_{1} where netID ={2} and startTime<='{3}'order by startTime desc", cbo_rti.RefId, Trim(MainForm.pi.ProjectID).Replace("-", "_"), cbo_rti.NetId, UtilityClass.GetDateString(dtpFromValue))
        Dim lastal As DataSet = Nothing
        strSql1 = String.Format("select  distinct netID, startTime, Ref{0}_DoorAlarm from tbccHDAlarmData_{1} where netID ={2} and startTime>='{3}'and startTime<='{4}' order by startTime ", cbo_rti.RefId, Trim(MainForm.pi.ProjectID).Replace("-", "_"), cbo_rti.NetId, UtilityClass.GetDateString(dtpFromValue), UtilityClass.GetDateString(dtpToValue))
        Dim allAl As DataSet = Nothing
        Try


            lastal = SqlHelper.ExecuteDataset(strSql, Nothing)

            If lastal.Tables.Count = 0 OrElse lastal.Tables(0).Rows.Count = 0 Then
                lastal.Clear() : lastal.Dispose() : lastal = Nothing
                ' Return Nothing
            Else
                Dim n As DataRow = lastal.Tables(0).Rows.Item(0)
                Dim k As Integer = n(DoorState_tablename)
                If k = 0 Then
                    dtAlBg.Add(n("startTime"))
                End If

            End If

            allAl = SqlHelper.ExecuteDataset(strSql1, Nothing)
            If allAl.Tables.Count = 0 OrElse allAl.Tables(0).Rows.Count = 0 Then
                allAl.Clear() : allAl.Dispose() : allAl = Nothing
                'Return Nothing
                dtAlBg.Clear()
            Else

                For Each i As DataRow In allAl.Tables(0).Rows
                    Dim g As Integer = i(DoorState_tablename)

                    If g = 0 Then

                        If right = False Then

                            dtAlBg.Add(i("startTime"))
                        End If
                        right = True
                    ElseIf g = 1 Then
                        dtAlEnd.Add(i("startTime"))
                        right = False

                    End If

                Next
                If right = True Then
                    Dim time As DateTime = UtilityClass.GetDateString(dtpToValue)
                    dtAlEnd.Add(time)
                    right = False

                End If

            End If




        Catch ex As Exception
            If lastal IsNot Nothing Then
                lastal.Clear() : lastal.Dispose() : lastal = Nothing
            End If
            If allAl IsNot Nothing Then
                allAl.Clear() : allAl.Dispose() : allAl = Nothing
            End If

        End Try

        Dim dss As New DataSet("dss1")
        Dim dss_table As DataTable = dss.Tables.Add("hd")
        dss_table.Columns.Add("num", GetType(Object))
        dss_table.Columns.Add("hDate", GetType(DateTime))

        'distinct
        '时间间隔数据
        Dim iSeconds As Integer = HIST_SAVE_INTERVAL_TIME

        Select Case IntevalType
            Case "秒"
                If _Second > 0 Then
                    iSeconds = _Second
                End If

            Case "分钟"
                iSeconds = _Minute * 60

            Case "小时"
                iSeconds = _Hour * 3600

            Case Else
                Return Nothing
        End Select

        tArray.Clear()
        hArray.Clear()
        strSql = String.Format("select count(distinct a.hDate) num, a.hdate")


        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                Dim columnName As String = "AI" & Trim(apti.PortNo.ToString)
                strSql &= String.Format(",a.{0}", "AI" & Trim(apti.PortNo.ToString))
                dss_table.Columns.Add(columnName, GetType(String))
                If apti.PortNo <= 9 Then
                    tArray.Add(columnName)
                Else
                    hArray.Add(columnName)
                End If
            End If

            row = apts.GetAiGroupList.Count
        Next

        'If is_firstrun = True Then '当前冷库没有配置AI
        '    msg.Show("指定冷库尚未配置数据端口")
        'End If

        Dim diopts As DiDoPortTypeService = New DiDoPortTypeService(cbo_rti)

        Dim DoorState_tablename1 = String.Format("Ref{0}_DoorState", cbo_rti.RefId.ToString)
        'Dim DoorState_tablename = String.Format("Ref1_DoorState")
        ' Dim LostPowerState_tablename = String.Format("Ref1_LostPowerState", cbo_rti.RefId.ToString)
        Dim LostPowerState_tablename = String.Format("Ref{0}_LostPowerState", cbo_rti.RefId.ToString)

        Dim RefAlarmState_tablename = String.Format("Ref{0}_RefAlarmState", cbo_rti.RefId.ToString)
        Dim SoundOutputState_tablename = String.Format("Ref{0}_SoundOutputState", cbo_rti.RefId.ToString)

        For Each diopti As DiDoPortTypeItem In diopts.GetDioGroupList()
            If diopti.DoorStatusPort >= 1 Then
                strSql &= String.Format(",a." & DoorState_tablename1)
                alarmstatus_DoorValid = True
                dss_table.Columns.Add(DoorState_tablename1, GetType(String))
            End If

            If diopti.LostPowerPort >= 1 Then
                strSql &= String.Format(",a." & LostPowerState_tablename)
                alarmstatus_LosPowerValid = True
                dss_table.Columns.Add(LostPowerState_tablename, GetType(String))
            End If

            If diopti.RefAlarmPort >= 1 Then
                strSql &= String.Format(",a." & RefAlarmState_tablename)
                alarmstatus_RefAlarmValid = True
                dss_table.Columns.Add(RefAlarmState_tablename, GetType(String))

            End If

            If diopti.SoundAlarmPort >= 1 Then
                strSql &= String.Format(",a." & SoundOutputState_tablename)
                alarmstatus_SoundAlarmValid = True
                dss_table.Columns.Add(SoundOutputState_tablename, GetType(String))
            End If
        Next

        ' dss_table.Columns.Add("Ref1_LostPowerState", GetType(String))

        strSql &= String.Format(" From tbccHDData_{0}_{1} AS a   Where  a.hdate between '{4}' and '{5}' and ((HOUR(a.hdate)*3600+ MINUTE(a.hdate)*60+SECOND(a.hdate))- (HOUR('{4}')*3600+ MINUTE('{4}')*60+SECOND('{4}'))) % {6} =0 group by a.hdate order by a.hDate", Trim(MainForm.pi.ProjectID).Replace("-", "_"), cbo_rti.NetId, Trim(cbo_rti.ProjectID).Replace("-", "_"), FNETID, UtilityClass.GetDateString(dtpFromValue), UtilityClass.GetDateString(dtpToValue), iSeconds)

        Dim ds As DataSet = Nothing
        Dim tmpObj As Object



        Try
            ds = SqlHelper.ExecuteDataset(strSql, Nothing)

            If ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then
                ds.Clear() : ds.Dispose() : ds = Nothing
                Return Nothing
            End If


            Dim dtStart As DateTime
            dtStart = AdjustDateTime(dtpFromValue)

            Dim proIndex As Integer = 0
            Dim dtTmp As DateTime
            'If alarmstatus_DoorValid = True Then
            '    ds.Tables(0).Columns.Add("Ref_DoorState")
            'End If

            For Each r As DataRow In ds.Tables(0).Rows
                If Me.bwSearch.CancellationPending Then
                    Return Nothing '取消查询
                End If

                dtTmp = r("hdate")
                IsFind = False
                tmpObj = r(tArray(0))
                If UtilityClass.IsNotNullEmpty(tmpObj) = True Then
                    If tmpObj = INVALID_DATA Then
                        r.Delete()
                        IsFind = True

                    End If
                End If

                If IsFind = True Then
                    Continue For
                Else

                End If
                dss_table.Rows.Add(r.ItemArray)   '将数据添加到新结构中为处理中文字问题        

            Next

            For k As Integer = 0 To dss_table.Rows.Count - 1
                Dim r As DataRow = dss_table.Rows(k)


                If Me.bwSearch.CancellationPending Then
                    Return Nothing '取消查询
                End If

                dtTmp = r("hdate")


                r = r


                If alarmstatus_DoorValid = True Then
                    If Not IsDBNull(r(DoorState_tablename1)) Then '库门状态
                        If r(DoorState_tablename1) = g_On Then
                            r(DoorState_tablename1) = "开启"
                        Else
                            r(DoorState_tablename1) = "关闭"
                        End If

                    End If

                    'If dtAlBg.Count = 0 Then
                    '    r(DoorState_tablename1) = "正常"
                    'Else
                    '    For i As Integer = 0 To dtAlBg.Count - 1

                    '        Dim bgtime As DateTime = CType(dtAlBg.Item(i), DateTime)
                    '        Dim endtime As DateTime = CType(dtAlEnd.Item(i), DateTime)

                    '        If bgtime <= dtTmp AndAlso dtTmp <= endtime Then
                    '            r(DoorState_tablename1) = "报警"
                    '            Exit For
                    '        Else
                    '            r(DoorState_tablename1) = "正常"
                    '        End If
                    '        dirow = dirow + 1
                    '        'End If
                    '    Next
                    'End If

                End If
                If alarmstatus_LosPowerValid = True Then
                    If Not IsDBNull(r(LostPowerState_tablename)) Then '缺项报警状态
                        If r(LostPowerState_tablename) = g_On Then
                            r(LostPowerState_tablename) = "预警"
                        Else
                            r(LostPowerState_tablename) = "正常"
                        End If
                    End If
                End If

                'If Not IsDBNull(r("Ref1_LostPowerState")) Then '缺项报警状态
                '    If r("Ref1_LostPowerState") = g_On Then
                '        r("Ref1_LostPowerState") = "报警"
                '    Else
                '        r("Ref1_LostPowerState") = "正常"
                '    End If
                '    '  dirow = dirow + 1
                'End If


                If alarmstatus_RefAlarmValid = True Then
                    If Not IsDBNull(r(RefAlarmState_tablename)) Then '冷库报警状态
                        If r(RefAlarmState_tablename) = AlarmType.ALARMSTATE.ALARM Then
                            r(RefAlarmState_tablename) = "报警"
                        ElseIf r(RefAlarmState_tablename) = AlarmType.ALARMSTATE.NORMAL Then
                            r(RefAlarmState_tablename) = "正常"
                        ElseIf r(RefAlarmState_tablename) = AlarmType.ALARMSTATE.PREALARM Then
                            r(RefAlarmState_tablename) = "预警"
                        End If

                    End If
                End If

                If alarmstatus_SoundAlarmValid = True Then
                    If Not IsDBNull(r(SoundOutputState_tablename)) Then '声光报警状态
                        If r(SoundOutputState_tablename) = g_On Then
                            r(SoundOutputState_tablename) = "报警"
                        Else
                            r(SoundOutputState_tablename) = "正常"
                        End If
                    End If
                End If

                ' End If
                proIndex += 1
                ReportProgress((proIndex / dss.Tables(0).Rows.Count) * 100) '报告进度
                'dss_table.AcceptChanges()
            Next

            dtAlBg.Clear()
            dtAlEnd.Clear()
            dss.AcceptChanges()
            ds.AcceptChanges()

            If dss.Tables(0).Rows.Count = 0 Then
                dss.Clear() : dss.Dispose() : dss = Nothing
                Return Nothing
            End If
            If ds.Tables(0).Rows.Count = 0 Then
                ds.Clear() : ds.Dispose() : ds = Nothing
                Return Nothing
            End If

        Catch ex As Exception
            'msg.Show("指定时间范围没有数据,请重新设置时间范围")
            If dss IsNot Nothing Then
                dss.Clear() : dss.Dispose() : dss = Nothing
            End If

            If ds IsNot Nothing Then
                ds.Clear() : ds.Dispose() : ds = Nothing
            End If
        End Try

        Return dss
    End Function


    ''' <summary>
    ''' 检查时间范围是否合法
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckValidate() As Boolean
        If Me.dtpTo.Value < Me.dtpFrom.Value Then
            msg.ShowWarning("起始时间不能大于终止时间。")
            Me.dtpFrom.Focus()
            Return False
        End If

        '限制查询的历史记录数量
        Dim ratio As Integer = 1
        Select Case Me.cboIntevalType.Text.Trim()
            Case "秒"
                ratio = 1
            Case "分钟"
                ratio = 6

            Case "小时"
                ratio = 360
            Case Else
                Return False
        End Select

        If Me.dtpTo.Value > Me.dtpFrom.Value.AddDays(7 * ratio) Then
            msg.ShowWarning(String.Format("查询的时间间隔不能超过{0}天", 7 * ratio))
            Me.dtpFrom.Focus()
            Return False
        End If

        Return True
    End Function

    Private Function AdjustDateTime(ByVal dt As DateTime) As DateTime
        Return dt.AddSeconds(-dt.Second Mod HIST_SAVE_INTERVAL_TIME)
    End Function

    Private Sub HDViewForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.DataGridView1.AutoGenerateColumns = False

        Me.cboIntevalType.SelectedIndex = 2
        Me.cboRef.SelectedIndex = -1

        Dim dt As DateTime = UtilityClass.GetDateString(Now)
        dtpTo.Value = dt
        dtpFrom.Value = dt.ToLongDateString()
        'dtpFrom.Value = dtpFrom.Value.AddMonths(-1)
        dtpFrom.Value = dtpFrom.Value.AddDays(-1)
        LoadRef()

    End Sub

    Private Sub LoadRef()
        Dim rts As RefTypeService = New RefTypeService(MainForm.pi)

        For Each rti As RefTypeItem In rts.GeRefGroupList()
            cboRef.Items.Add(rti)
        Next

        cboRef.SelectedIndex = -1
        btnRefresh.Enabled = False
        btnPrint.Enabled = False
    End Sub
    Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
        Export()
    End Sub

    Private Sub Export()
        Dim dt As DataTable
        dt = CType(Me.DataGridView1.DataSource, DataTable)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            msg.Show("没有数据")
            Exit Sub
        End If

        Dim excel As New Excel.Application

        'excel.Workbooks.Open(_excelFile)
        excel.Workbooks.Add()

        '  excel.Application.Workbooks.Add(True)
        excel.Visible = True
        Dim values(dt.Rows.Count, dt.Columns.Count) As Object

        For j As Integer = 0 To Me.DataGridView1.Columns.Count - 1
            values(0, j) = Me.DataGridView1.Columns(j).HeaderText
        Next

        For i As Integer = 0 To dt.Rows.Count - 1
            Dim r As DataRow = dt.Rows(i)
            For j As Integer = 0 To dt.Columns.Count - 2
                values(i + 1, j) = r(j + 1)
            Next
        Next

        Try
            excel.Range(excel.Cells(1, 1), excel.Cells(dt.Rows.Count, dt.Columns.Count)).Value = values
            'excel.Workbooks(1).PrintOut()
            'excel.DisplayAlerts = False
            'excel.Quit()
        Catch ex As Exception
            Debug.WriteLine("打印错误 " & ex.ToString())
        End Try
    End Sub

    Dim cols(100) As String
    Dim headers(100) As String

    Private Sub Print()
        Dim dt As DataTable
        dt = CType(Me.DataGridView1.DataSource, DataTable)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            msg.Show("没有数据")
            Exit Sub
        End If

        Dim objExcel As New Excel.Application

        'excel.Workbooks.Open(_excelFile)
        objExcel.Workbooks.Add()

        '  excel.Application.Workbooks.Add(True)
        'objExcel.Visible = True

        ReDim Preserve cols(100)


        Dim index As Integer = 0
        cols(index) = "序号"
        headers(index) = "序号"
        For i As Integer = 0 To Me.DataGridView1.Columns.Count - 1
            If Me.DataGridView1.Columns(i).Visible Then
                index += 1
                cols(index) = Me.DataGridView1.Columns(i).DataPropertyName
                headers(index) = Me.DataGridView1.Columns(i).HeaderText
            End If
        Next

        ReDim Preserve cols(index)


        'Dim values(dt.Rows.Count, dt.Columns.Count) As Object

        'For j As Integer = 0 To Me.DataGridView1.Columns.Count - 1
        '    values(0, j) = Me.DataGridView1.Columns(j).HeaderText
        'Next

        'For i As Integer = 0 To dt.Rows.Count - 1
        '    Dim r As DataRow = dt.Rows(i)
        '    For j As Integer = 0 To dt.Columns.Count - 2
        '        values(i + 1, j) = r(j + 1)
        '    Next
        'Next

        Dim values(dt.Rows.Count + 1, cols.Length) As Object

        For j As Integer = 0 To cols.Length
            values(0, j) = headers(j)
        Next

        Dim m_str As String
        For i As Integer = 0 To dt.Rows.Count - 1
            Dim r As DataRow = dt.Rows(i)
            values(i + 1, 0) = i + 1
            'values(i + 1, 0) = i
            For j As Integer = 1 To cols.Length - 1
                If j >= 2 Then
                    m_str = r(cols(j))

                    If String.Compare(m_str, "开") = 0 Then
                        m_str = "开"
                        values(i + 1, j) = "'" & String.Format("开")
                        Continue For
                    End If
                    If String.Compare(m_str, "报警") = 0 Then
                        m_str = "报警"
                        values(i + 1, j) = "'" & String.Format("报警")
                        Continue For
                    End If

                    If String.Compare(m_str, "关") = 0 Then
                        m_str = "关"
                        values(i + 1, j) = "'" & String.Format("关")
                        Continue For
                    End If
                    If String.Compare(m_str, "正常") = 0 Then
                        m_str = "正常"
                        values(i + 1, j) = "'" & String.Format("正常")
                        Continue For
                    End If



                    values(i + 1, j) = "'" & String.Format(Convert.ToSingle(m_str), "0.00")
                Else
                    values(i + 1, j) = r(cols(j))
                End If

            Next
        Next
        Dim pwd As String = System.Guid.NewGuid().ToString()
        Try
            objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, cols.Length)).Value = values
            objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, cols.Length)).Font.Size = 8

            '设置格式
            objExcel.Columns("A:AA").Select()
            objExcel.Selection.HorizontalAlignment = Excel.Constants.xlCenter
            objExcel.Selection.ColumnWidth = 10

            '序号
            objExcel.Columns("A:A").Select()
            objExcel.Selection.ColumnWidth = 5

            '监控时间
            objExcel.Columns("B:B").Select()
            objExcel.Selection.ColumnWidth = 15
            objExcel.Selection.NumberFormatLocal = "yyyy-mm-dd hh:mm:ss"

            'dirow = dt.Rows.Count - row - 1
            'Dim g As Integer
            'g = 3 + row
            objExcel.Range(objExcel.Cells(1, 3), objExcel.Cells(dt.Rows.Count, row + 2)).ColumnWidth = 4
            'objExcel.Range(objExcel.Cells(1, g), objExcel.Cells(dt.Rows.Count + 1, dirow)).ColumnWidth = 6
            'objExcel.Range(objExcel.Cells(1, g), objExcel.Cells(dt.Rows.Count + 1, dirow)).WrapText = True
            'objExcel.Range(objExcel.Cells(1, (3 + row)), objExcel.Cells(dt.Rows.Count + 1, dirow)).Font = 10

            dirow = 0

            Try
                objExcel.ActiveSheet.Protect(pwd, _
                            AllowFormattingCells:=False, _
                            AllowFormattingColumns:=False, _
                            AllowFormattingRows:=False, _
                            AllowInsertingColumns:=False, _
                            AllowInsertingRows:=False, _
                            AllowInsertingHyperlinks:=False, _
                            AllowDeletingColumns:=False, _
                            AllowDeletingRows:=False _
                )
            Catch ex As Exception
                objExcel.ActiveSheet.Protect(pwd)
            End Try

            With objExcel.ActiveSheet.PageSetup
                .LeftHeader = "" & Chr(10) & "" & Chr(10) & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & Chr(10) & "" & Chr(10) & ""
                .CenterHeader = String.Format("&""宋体,加粗""&20{0}温湿度查询", Me.cboRef.Text)
                .RightHeader = "" & Chr(10) & "" & Chr(10) & "共&N页 第&P页"
                .LeftFooter = "养护员："
                .CenterFooter = ""
                .RightFooter = "打印日期：&D &T"
                .LeftMargin = objExcel.Application.InchesToPoints(0.8)
                .RightMargin = objExcel.Application.InchesToPoints(0.5)
                .TopMargin = objExcel.Application.InchesToPoints(0.77)
                .BottomMargin = objExcel.Application.InchesToPoints(0.68)
                .HeaderMargin = objExcel.Application.InchesToPoints(0.12)
                .FooterMargin = objExcel.Application.InchesToPoints(0.5)
                .PrintHeadings = False
                .PrintGridlines = True
                '.PrintComments = objExcel.xlPrintNoComments
                ''.PrintQuality = 300
                .CenterHorizontally = False
                .CenterVertically = False
                '.Orientation = objExcel.xlPortrait
                .Draft = False
                .Orientation = Excel.XlPageOrientation.xlLandscape '横向打印
                '.PaperSize = objExcel.xlPaperA4
                '.FirstPageNumber = objExcel.xlAutomatic
                '.Order = objExcel.xlDownThenOver
                '.BlackAndWhite = False
                '.Zoom = 100
                '.PrintErrors = objExcel.xlPrintErrorsDisplayed

                .FitToPagesWide = 1
                .FitToPagesTall = 1
                .PrintTitleRows = "$1:$1"

            End With
            'excel.printpreview()
            'excel.PrintPreview()

            objExcel.Visible = True
            objExcel.ActiveWindow.SelectedSheets.PrintPreview()

            'excel.Workbooks(1).PrintOut()
            'excel.DisplayAlerts = False
            'excel.Quit()
        Catch ex As Exception
            Debug.WriteLine("打印错误" & ex.ToString())
            msg.Show(ex.Message)
        Finally
            Try
                'objExcel.Workbooks.Close()
                objExcel.DisplayAlerts = False
                objExcel.Quit()
                objExcel = Nothing
                'System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel)
                GC.Collect()
            Catch ex As Exception
                Debug.WriteLine(ex.ToString())
            End Try

        End Try
    End Sub

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Print()
    End Sub

    Private Sub cboIntevalType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboIntevalType.SelectedIndexChanged, cboRef.SelectedIndexChanged
        Me.btnPrint.Enabled = False

        HideAll()

        Select Case Me.cboIntevalType.SelectedIndex
            Case 0
                'second
                Me.cboSecond.Visible = True
                Me.cboSecond.SelectedIndex = 0

            Case 1
                'minute
                Me.nudMinute.Visible = True
                Me.nudMinute.Value = 1

            Case 2
                'hour
                Me.nudHour.Visible = True
                Me.nudHour.Value = 1

        End Select

        If cboRef.SelectedIndex <> -1 Then
            btnRefresh.Enabled = True
        End If

    End Sub

    Private Sub HideAll()
        Me.cboSecond.Visible = False
        Me.nudHour.Visible = False
        Me.nudMinute.Visible = False
    End Sub


    Private Sub cboSecond_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboSecond.SelectedIndexChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Sub nudHour_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudHour.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Sub nudMinute_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudMinute.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Sub dtpFrom_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpFrom.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Sub dtpTo_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpTo.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Delegate Sub VoidMethodHandler(ByVal obj As Object)
    Private Sub bwSearch_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwSearch.DoWork
        Dim ds As DataSet
        e.Result = New Object() {True, Nothing}

        '设置状态
        Dim str As String = String.Format("正在查询{0}历史数据……", e.Argument(0))
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf SetSearchState), str)
        Else
            SetSearchState(str)
        End If

        '查询数据
        ds = RefreshData(e.Argument)

        '添加数据至DataGridView
        If ds IsNot Nothing Then
            Dim obj As Object = New Object() {e.Argument(0), ds}
            If Me.InvokeRequired Then
                Me.Invoke(New VoidMethodHandler(AddressOf AddDataToGridView), obj)
            Else
                AddDataToGridView(obj)
            End If
        Else
            e.Result(0) = False '无数据
        End If

        e.Result(1) = Me.bwSearch.CancellationPending
    End Sub

    Private Sub bwSearch_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwSearch.ProgressChanged
        Me.pbSearch.Value = e.ProgressPercentage
    End Sub

    Private Sub bwSearch_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwSearch.RunWorkerCompleted
        Me.pnlSearch.Visible = False

        If e.Result(0) = True Then
            Me.btnExport.Enabled = True
            Me.btnPrint.Enabled = True
        ElseIf Not e.Result(1) Then '过滤取消操作
            Me.btnExport.Enabled = False
            Me.btnPrint.Enabled = False
            msg.Show("指定时间范围没有数据,请重新设置时间范围")
        End If

        AfterRefreshControlState()
        GC.Collect()

        If e.Result(1) Then
            msg.Show("操作已取消")
        End If

    End Sub
    Private Sub AddDataGridViewColumns(ByVal obj As Object)
        Dim m_index As Integer
        Dim cbo_rti As RefTypeItem = obj
        Dim apts As AiPortTypeService = New AiPortTypeService(cbo_rti)

        '时间列
        m_index = Me.DataGridView1.Columns.Add("hDate", "时间")
        Me.DataGridView1.Columns(m_index).DataPropertyName = "hDate"
        Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
        Me.DataGridView1.Columns(m_index).DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss"

        'AI列
        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                m_index = Me.DataGridView1.Columns.Add("AI" & Trim(apti.PortNo.ToString), apti.PortName)
                Me.DataGridView1.Columns(m_index).DataPropertyName = "AI" & Trim(apti.PortNo.ToString)
                'Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            End If
        Next

        'DIO列
        Dim diopts As DiDoPortTypeService = New DiDoPortTypeService(cbo_rti)

        Dim DoorState_tablename = String.Format("Ref{0}_DoorState", cbo_rti.RefId.ToString)
        Dim LostPowerState_tablename = String.Format("Ref{0}_LostPowerState", cbo_rti.RefId.ToString)
        Dim RefAlarmState_tablename = String.Format("Ref{0}_RefAlarmState", cbo_rti.RefId.ToString)
        Dim SoundOutputState_tablename = String.Format("Ref{0}_SoundOutputState", cbo_rti.RefId.ToString)
        For Each diopti As DiDoPortTypeItem In diopts.GetDioGroupList()
            If diopti.DoorStatusPort >= 1 Then

                m_index = Me.DataGridView1.Columns.Add(DoorState_tablename, "库门开关状态")
                Me.DataGridView1.Columns(m_index).DataPropertyName = DoorState_tablename
                Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
                'Me.DataGridView1.Columns(m_index).ValueType = GetType(System.Object)
            End If

            If diopti.LostPowerPort >= 1 Then
                m_index = Me.DataGridView1.Columns.Add(LostPowerState_tablename, "断电预警状态")
                Me.DataGridView1.Columns(m_index).DataPropertyName = LostPowerState_tablename
                Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            End If

            If diopti.RefAlarmPort >= 1 Then
                m_index = Me.DataGridView1.Columns.Add(RefAlarmState_tablename, "冷库报警状态")
                Me.DataGridView1.Columns(m_index).DataPropertyName = RefAlarmState_tablename
                Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
                'Me.DataGridView1.Columns(m_index).ValueType = GetType(System.Object)
            End If

            If diopti.SoundAlarmPort >= 1 Then
                m_index = Me.DataGridView1.Columns.Add(SoundOutputState_tablename, "声光报警状态")
                Me.DataGridView1.Columns(m_index).DataPropertyName = SoundOutputState_tablename
                Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
                ' Me.DataGridView1.Columns(m_index).ValueType = GetType(System.Object)
            End If
        Next
        ''If diopti.LostPowerPort >= 1 Then
        'm_index = Me.DataGridView1.Columns.Add(LostPowerState_tablename, "断电报警状态")
        'Me.DataGridView1.Columns(m_index).DataPropertyName = LostPowerState_tablename
        ''Me.DataGridView1.Columns(m_index).DefaultHeaderCellType = GetType(String)
        'Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
        ''Me.DataGridView1.Columns(m_index).ValueType = GetType(System.Object)

        ''End If
    End Sub
    Private Sub AddDataToGridView(ByVal obj As Object)
        AddDataGridViewColumns(obj(0))
        Me.DataGridView1.DataSource = obj(1).Tables(0)

    End Sub
    Private Sub SetSearchState(ByVal obj As Object)
        Me.lblSearchState.Text = obj
    End Sub
    Private Sub ReportProgress(ByVal value As Integer)
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf ReportProgressMethod), value)
        Else
            ReportProgressMethod(value)
        End If
    End Sub
    Private Sub ReportProgressMethod(ByVal obj As Object)
        Me.bwSearch.ReportProgress(obj)
    End Sub

    Private Sub HDViewForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        DisposeBackWorker()
    End Sub

    Private Sub DisposeBackWorker()
        If Me.bwSearch IsNot Nothing Then
            Me.bwSearch.CancelAsync()
            Me.bwSearch.Dispose() : Me.bwSearch = Nothing
        End If
        GC.Collect()
    End Sub

    Private Sub DataGridView1_CellPainting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
        If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 Then
            If Me.DataGridView1.Columns(e.ColumnIndex).Name.StartsWith("Ref") Then
                Dim cell As DataGridViewCell = Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
                If cell.Value.Equals("报警") Then
                    cell.Style.ForeColor = Color.Red
                End If
                If cell.Value.Equals("预警") Then
                    cell.Style.ForeColor = Color.Orange
                End If

            End If
        End If
    End Sub

End Class